package com.xuyuan.interview.scene.coupon;

import com.xuyuan.interview.scene.CouponContext;
import com.xuyuan.interview.scene.api.Coupon;
import com.xuyuan.interview.scene.api.CouponCondition;
import com.xuyuan.interview.scene.entity.Order;
import com.xuyuan.interview.scene.entity.Product;

import java.math.BigDecimal;
import java.util.ArrayList;
import java.util.List;
import java.util.Set;

public class CombinationCoupon extends CouponCondition {
    private List<Coupon> coupons = new ArrayList<>();

    @Override
    public String getCouponName() {
        return this.getClass().getSimpleName();
    }

    @Override
    public Order applyDiscount(Order order) {
        Set<String> allCouponName = CouponContext.getAllCouponName();
        allCouponName.remove(this.getCouponName());
        coupons.forEach(coupon -> {
            if (allCouponName.contains(coupon.getCouponName())) {
                coupon.applyDiscount(order);
            }
        });
        return order;
    }

    @Override
    public boolean isSatisfied(Order order, Product product, int userLevel) {
        for (Coupon coupon : coupons) {
            if (!coupon.isSatisfied(order, product, userLevel)) return false;
        }
        return true;
    }

    @Override
    public BigDecimal findPriority(Order order) {
        coupons.forEach(coupon -> {
            coupon.applyDiscount(order);
        });
        return order.getTotalPrice().subtract(order.getGifts().stream().map(Product::getProductPrice).max(BigDecimal::compareTo).orElse(BigDecimal.ZERO));
    }

}
